/**  定义Admin相关的接口 */
const express = require("express");
const router = express.Router();
const Joi = require("joi");
const Response = require("../utils/Response.js");

// 引入mysql连接池
const pool = require("../utils/db.js");

const jwt = require("jsonwebtoken");
const SECRET_KEY = "JWT_SECRET_KEY";

/**
 * 处理登录业务
 */
router.post("/user/login", (req, resp) => {
  let { username, password } = req.body;
  // 表单验证
  let schema = Joi.object({
    username: Joi.string().required().pattern(new RegExp("^\\w{3,15}$")), // 必填
    password: Joi.string().required().pattern(new RegExp("^\\w{6,15}$")), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 查询数据库，账号密码是否填写正确
  let sql = "select * from mac_admin where username=? and password=MD5(?)";
  pool.query(sql, [username, password], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      resp.send(Response.error(1001, "账号密码输入错误"));
    } else {
      // 获取登录用户对象
      let user = result[0];
      // 为该用户颁发一个token字符串，未来该客户端若做发送其他请求，则需要在请求Header中携带token，完成状态管理。
      let payload = { id: user.id, nickname: user.nickname };
      let token = jwt.sign(payload, SECRET_KEY, { expiresIn: "1d" });
      // 返回user对象与token字符串
      user.password = undefined;
      resp.send(Response.ok({ user, token }));
    }
  });
});

// 添加管理员
router.post("/admin/add", (req, res) => {
  var { id, username, password, nickname, phone, email } = req.body;
  let sql =
    "insert into mac_admin (id,username,password,nickname,phone,email) values (?,?,MD5(?),?,?,?)";
  pool.query(
    sql,
    [id, username, password, nickname, phone, email],
    (err, r) => {
      if (err) {
        throw err;
      }
      console.log(r);
    }
  );
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

// 删除
router.delete("/admin/del", (req, resp) => {
  let { id } = req.query;
  // 执行删除业务
  let sql = "delete from Mac_Admin where id = ?";
  pool.query(sql, [id], (error, result) => {
    if (error) {
      throw err;
    }
    if (result.affectedRows === 0) {
      resp.send({
        code: 400,
        msg: "删除失败",
      });
    } else {
      resp.send({
        code: 200,
        msg: "删除成功",
        data: result,
      });
    }
  });
});
// 查询所有
router.get("/admin", (req, res) => {
  var obj = req.query;
  console.log(obj);

  pool.query("select * from Mac_Admin", [obj], (err, r) => {
    if (err) {
      throw err;
    }
    console.log(r);
    if (r.length === 0) {
      res.send({
        code: 400,
        msg: "查询失败",
      });
    } else {
      // 接口规范，返回的结果是对象，包含有状态码（人为规定），消息说明，如果需要返回数据，添加查询数据
      res.send({
        code: 200,
        msg: "查询成功",
        data: r,
      });
    }
  });
  // query属于异步操作，需要 把响应的结果放入到回调函数的内部
});
// 将router对象导出
module.exports = router;
